package com.dts.controller;

import com.alibaba.fastjson.JSON;
import com.dts.entity.DateName;
import com.dts.entity.Hello;
import org.springframework.core.io.Resource;
import org.springframework.core.io.UrlResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import java.io.File;
import java.io.IOException;
import java.net.MalformedURLException;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Map;

@Controller
public class UserController {

    @RequestMapping("/example")
    public ModelAndView example() {
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.addObject("message", "Hello, World!");
        modelAndView.setViewName("exampleView");
        return modelAndView;
    }

    @RequestMapping("/dis")
    public String display1(@Validated Hello hello, BindingResult result, Model model) {
        if (result.hasErrors()) {
            System.out.println("error:" + result.getAllErrors());
            model.addAttribute("message", result.getAllErrors());
        } else {
            model.addAttribute("message", "Hello, World!");
        }
        return "index";
    }

    @RequestMapping("/rest/{id}")
    public String rest(@PathVariable("id") String id, Model model) {
        model.addAttribute("message", id);
        return "index";
    }

    @RequestMapping(value = "/example", method = RequestMethod.GET)
    public String example(Map<String, Object> map) {
        map.put("message", "Hello, World!");
        return "exampleView";
    }

    @RequestMapping("/hello")
    public String display(Model model) {
        model.addAttribute("hello", new Hello());
        return "index";
    }

    @RequestMapping(value = "/user", produces = "text/json;charset=UTF-8")
    @ResponseBody()
    @CrossOrigin(originPatterns = "*", allowCredentials = "true")
    public String display1(DateName dateName) {
        return JSON.toJSONString(dateName);
    }

    @RequestMapping(value = "/user2")
    @ResponseBody()
    @CrossOrigin(originPatterns = "*", allowCredentials = "true")
    public String display2(DateName dateName) {
        return JSON.toJSONString(dateName);
    }

    @RequestMapping("/file")
    public String file(@RequestParam(value = "file") MultipartFile file) {
        if (!file.isEmpty()) {
            try {
                // 保存文件到指定目录
                String filePath = "D:\\cxdownload\\" + file.getOriginalFilename();
                file.transferTo(new File(filePath));
                return "redirect:/index.jsp";
            } catch (IOException e) {
                e.printStackTrace();
                return "redirect:/error.jsp";
            }
        } else {
            return "redirect:/error.jsp";
        }
    }

    @GetMapping("/download")
    public ResponseEntity<Resource> downloadFile(@RequestParam("file") String fileName) {
        try {
            Path path = Paths.get("D:\\cxdownload\\" + fileName);
            Resource resource = new UrlResource(path.toUri());
            if (resource.exists() || resource.isReadable()) {
                return ResponseEntity.ok()
                        .header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + resource.getFilename() + "\"")
                        .body(resource);
            } else {
                throw new RuntimeException("Could not read the file!");
            }
        } catch (MalformedURLException e) {
            throw new RuntimeException("Error: " + e.getMessage());
        }
    }
}